package com.wechat.developer.controller;

import com.alibaba.fastjson.JSON;
import com.wechat.developer.base.RedisUtils;
import com.wechat.developer.mybatis.mapping.WechatChannelConfigMapper;
import com.wechat.developer.mybatis.model.WechatChannelConfig;
import com.wechat.developer.utils.WeChatSignUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * @ProjectName: developer
 * @Package: com.wechat.developer.controller
 * @Description: 开发者基础功能接口
 * @Author: tdl
 * @CreateDate: 2018/11/6 下午4:05
 **/
@RestController
@RequestMapping(value = "/dev")
public class BaseController {

    @Value("${api.token}")
    String tokenUri;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private WechatChannelConfigMapper wechatChannelConfigMapper;

    /**
     * 验证开发者服务器
     *
     * @param signature
     * @param timestamp
     * @param nonce
     * @param echostr
     * @param channelId 渠道Id，直接设置在公众号服务器地址上，才能保证验证时拿到这个参数
     * @return echostr || "error"
     */
    @GetMapping(value = "/bind")
    public String bindDeveloper(@RequestParam String signature, @RequestParam String timestamp, @RequestParam String nonce, @RequestParam String echostr, @RequestParam String channelId) {
        WechatChannelConfig channel = wechatChannelConfigMapper.selectByPrimaryKey(channelId);

        if (channel != null) {
            String token = channel.getChannelMsgToken();
            if (WeChatSignUtil.checkSignature(signature, timestamp, nonce, token)) {
                return echostr;
            }
        }
        return "error";
    }

    /**
     * 获取开发者ACCESS_TOKEN
     *
     * @param channelId 渠道Id
     * @return accessToken
     */
    @GetMapping(value = "/token")
    public String fetchToken(@RequestParam String channelId) {
        if (StringUtils.isEmpty(channelId)) {
            return null;
        }
        String key = String.format("wxdev:channel:%s:accessToken", channelId);
        WechatChannelConfig channel = wechatChannelConfigMapper.selectByPrimaryKey(channelId);

        if (channel == null) {
            return null;
        }
        String appid = channel.getChannelAppid();
        String secret = channel.getChannelAppsecret();
        String accessToken = (String) redisUtils.get(key);

        if (StringUtils.isEmpty(accessToken)) {
            Long keyExpire = 7200L;
            String url = String.format("%s&appid=%s&secret=%s", tokenUri, appid, secret);
            String result = restTemplate.getForObject(url, String.class);
            Map resultMap = JSON.parseObject(result);

            if (resultMap.containsKey("access_token")) {
                accessToken = (String) resultMap.get("access_token");
                redisUtils.set(key, accessToken, keyExpire);
            }
        }

        return accessToken;
    }
}
